from django.shortcuts import render, redirect
from django.contrib.contenttypes.models import ContentType
from read_statistics.utils import get_seven_days_read_data, get_today_hot_data, \
                                  get_yesterday_hot_data, get_seven_days_hot_data
from blog.models import Blog
from django.core.cache import cache   # 这是默认的cache，若导入的是caches要进行额外的设置
from django.contrib.auth import authenticate, login
from django.urls import reverse



def home(request):
    blog_content_type = ContentType.objects.get_for_model(Blog) # 获得的是Blog实例化的对象
    dates, read_nums = get_seven_days_read_data(blog_content_type)  # 获得7天内每一天的阅读量之和
    today_hot_data = get_today_hot_data(Blog)  # 今日博客阅读量排行列表（queryset列表（列表中装的每一个博客的对象））
    yesterday_hot_data = get_yesterday_hot_data(Blog)  # 昨日博客阅读量排行列表（queryset列表（列表中装的每一个博客的对象））
    #seven_days_hot_data = get_seven_days_hot_data(Blog)  # 7日博客阅读量排行(queryset列表（列表中装的每一个博客的各属性字典）)
    context = {}

    # 获取7天热门博客的缓存数据
    seven_days_hot_data = cache.get('seven_days_hot_data')
    if seven_days_hot_data is None:
        seven_days_hot_data = get_seven_days_hot_data(Blog)   # 7日博客阅读量排行(queryset列表（列表中装的每一个博客的各属性字典）)
        cache.set('seven_days_hot_data', seven_days_hot_data, 3600)

    # 传给前端使用数据
    context['dates'] = dates
    context['read_nums'] = read_nums
    context['today_hot_data'] = today_hot_data
    context['yesterday_hot_data'] = yesterday_hot_data
    context['seven_days_hot_data'] = seven_days_hot_data
    return render(request, 'home.html', context)

